<template>
  <div class="login">
    <div class="login-container">
      <n-form
        ref="formRef"
        label-width="auto"
        label-placement="left"
        :model="form"
        :rules="rules"
      >
        <n-form-item
          label="用户名"
          path="username"
        >
          <n-input
            v-model:value="form.username"
            placeholder="请输入用户名"
          />
        </n-form-item>
        <n-form-item
          label="密码"
          path="password"
        >
          <n-input
            v-model:value="form.password"
            placeholder="请输入密码"
            type="password"
          />
        </n-form-item>
        <n-form-item label="">
          <n-button
            type="primary"
            style="width: 100%"
            @click="handleLogin"
          >
            登录
          </n-button>
        </n-form-item>
      </n-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import type { FormInst } from 'naive-ui'
  import { loginUser } from '@/api/login'
  import { useRouter } from 'vue-router'
  import appStore from '@/store'

  const router = useRouter()
  const { setToken } = appStore.useUserStore
  const formRef = ref<FormInst | null>(null)
  // 表单
  const form = ref({
    username: '', // 账号
    password: '' // 密码
  })

  // 校验
  const rules = {
    username: {
      required: true,
      message: '请输入账号',
      trigger: 'blur'
    },
    password: {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    }
  }

  // 登录
  const handleLogin = () => {
    const { username, password } = form.value
    formRef.value?.validate().then(() => {
      loginUser({ username, password }).then(res => {
        setToken(res.data.token)
        router.push('/')
      })
    })
  }
</script>

<style scoped lang="scss">
  .login {
    width: 100vw;
    height: 100vh;
    .login-container {
      position: fixed;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      height: 340px;
      width: 600px;
      border: 1px solid #f0f0f0;
      padding: 64px;
      box-sizing: border-box;
    }
  }
</style>
@/store/user
